<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <link rel="stylesheet" href="/lib/element-ui/index.css">
    <style>
        .float-right-flex {
            align-self: end;
        }
        .float-right {
            float: right;
        }
    </style>
</head>
<body>
<div style="display: flex; justify-content: center;">
    <div id="app" style="display: flex; flex-direction: column; justify-items: center; padding: 20px; min-width: 1000px;">
        <div style="display: flex; justify-content: space-between;">
            <span>User: {{userId}}</span>
            <div>
                <el-button @click="location.href = '/tools.html'">Tools</el-button>
                <el-button @click="() => { groupInEditing = {}; upsertGroupDialog = true; }" type="primary">AddGroup</el-button>
            </div>
        </div>
        <el-collapse v-model="activeName" accordion @change="changeActiveGroup">
            <el-collapse-item v-for="(group, idx) in groupList" :title="group.name" :name="idx">
                <div>
                    <div style="display: flex; justify-content: space-between;">
                        <div style="display: flex;">
                            <el-input v-model="searchKeyword" style="max-width: 360px; margin-right: 20px;" type="text"></el-input>
                            <el-button @click="search">Search</el-button>
                            <el-button @click="clearSearch">Clear</el-button>
                        </div>
                        <div>
                            <el-button @click="deleteGroup" type="danger">DeleteGroup</el-button>
                            <el-button @click="refreshGroupPrice">RefreshPosition</el-button>
                            <el-button @click="() => { groupInEditing = activeGroup; upsertGroupDialog = true; }" type="primary">EditGroup</el-button>
                        </div>
                    </div>
                    <div v-show="searchResult.length !== 0">
                        <el-table
                                :data="searchResult"
                                stripe
                                style="width: 100%">
                            <el-table-column
                                    prop="code"
                                    label="Code"
                                    width="180">
                            </el-table-column>
                            <el-table-column
                                    prop="name"
                                    label="名称"
                                    width="180">
                            </el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button size="mini" @click="addGroupItem(scope.row)" type="success" round>加入Group</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <el-table
                            :ref="`groupTable${idx}`"
                            :data="groupItemList"
                            stripe
                            style="width: 100%">
                        <el-table-column
                                prop="code"
                                label="Code"
                                width="120">
                        </el-table-column>
                        <el-table-column
                                prop="name"
                                label="名称"
                                width="auto">
                        </el-table-column>
                        <el-table-column
                                prop="count"
                                label="数量"
                                sortable
                                width="120">
                        </el-table-column>
                        <el-table-column
                                prop="price"
                                label="市价"
                                width="120">
                        </el-table-column>
                        <el-table-column
                                prop="total"
                                label="市值"
                                width="120">
                        </el-table-column>
                        <el-table-column
                                prop="position"
                                label="仓位(%)"
                                sortable
                                width="120">
                            <template slot-scope="scope">
                                <div>{{scope.row.position === undefined ? '' : scope.row.position.toFixed(1)}}</div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="160" v-if="!hideTableOpCol">
                            <template slot-scope="scope">
                                <div style="display: flex; justify-items: center;" v-if="!scope.cash">
                                    <div v-show="!scope.row.cash">
                                        <el-button size="mini" @click="() => {
                                            itemInEditing = scope.row
                                            updateGroupItemDialog = true
                                        }" type="primary">编辑</el-button>
                                        <el-button size="mini" @click="removeGroupItem(scope.row)" type="danger">删除</el-button>
                                    </div>
                                    <div v-show="scope.row.cash && !scope.row.last">
                                        <el-button size="mini" @click="() => {exportGroup(activeGroup)}" type="info">导出</el-button>
                                        <el-button size="mini" @click="importGroupDialog = true" type="info">导入</el-button>
                                    </div>
                                    <div v-show="scope.row.last">创建于：{{activeGroup.createTimeStr}}</div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div style="display: flex; justify-content: space-between; margin-top: 20px;">
                        <div style="display: flex;">
                        </div>
                        <div>
                            <el-button @click="snapshotPng(idx)" plain>Snapshot(Png)</el-button>
                            <el-button @click="() => hideTableOpCol = !hideTableOpCol" plain>{{hideTableOpCol ? '显示' : '隐藏'}}操作列</el-button>
                        </div>
                    </div>
                </div>
            </el-collapse-item>
        </el-collapse>

        <div v-if="snapshotImg">
            <el-image
                    :src="snapshotImg"
                    fit="fill"
            />
        </div>

        <div v-if="upsertGroupDialog">
            <edit-group
                    :close-dialog="() => { upsertGroupDialog = false; if (groupInEditing.id) { refreshGroupDetail(); } else { fetchGroups(); } }"
                    :group-info="groupInEditing"
                    :user-id="userId"
                    :visible="upsertGroupDialog"
            />
        </div>

        <div v-if="updateGroupItemDialog">
            <edit-group-item
                    :close-dialog="() => { updateGroupItemDialog = false; refreshGroupDetail(); }"
                    :item-in-editing="itemInEditing"
                    :visible="updateGroupItemDialog"
            />
        </div>

        <div v-if="importGroupDialog">
            <import-group
                    :close-dialog="() => importGroupDialog = false"
                    :group="activeGroup"
                    :visible="importGroupDialog"
            />
        </div>
    </div>
</div>
</body>
<script src="/lib/vue/vue.min.js"></script>
<script src="/lib/axios/axios.min.js"></script>
<script src="/lib/element-ui/index.js"></script>
<script src="/lib/html-to-image/html-to-image.js"></script>
<script src="/lib/moment/moment.min.js"></script>

<script src="/js/editGroup.js"></script>
<script src="/js/editGroupItemDialog.js"></script>
<script src="/js/importGroupDialog.js"></script>
<script>
    const userId = localStorage.getItem("userId") || 1;
    const vm = new Vue({
        el: '#app',
        data() {
            return {
                userId,
                activeName: 0,
                searchKeyword: '',
                searchResult: [],
                groupList: [],
                activeGroup: {},
                groupItemList: [],
                hideTableOpCol: false,
                updateGroupItemDialog: false,
                upsertGroupDialog: false,
                importGroupDialog: false,
                groupInEditing: {},
                itemInEditing: {},
                snapshotImg: undefined
            }
        },
        computed: {
        },

        methods: {
            search: async function () {
                const res = await axios.get(`/api/stock/search?keyword=${this.searchKeyword}`)
                this.searchResult = res.data
            },
            clearSearch: function () {
                this.searchKeyword = ''
                this.searchResult = []
            },
            addGroupItem: async function (row) {
                let sort = 100;
                if (this.groupItemList.length !== 0) {
                    sort = this.groupItemList[this.groupItemList.length - 1].sort || (this.groupItemList.length + 1) * 100
                }
                const res = await axios
                    .post(`/api/group/item?groupId=${this.activeGroup.id}&code=${row.code}&name=${row.name}&sort=${sort}`)
                console.log(res)
                this.refreshGroupDetail()
            },
            removeGroupItem: async function (row) {
                const res = await axios
                    .delete(`/api/group/item?id=${row.id}`)
                console.log(res)
                this.refreshGroupDetail()
            },

            refreshGroupDetail: async function () {
                this.activeGroup = await this.fetchGroupDetail(this.activeGroup.id)
            },

            fetchGroupDetail: async function (groupId) {
                const res = await axios.get(`/api/group/detail?groupId=${groupId}`)
                return res.data
            },
            fetchGroups: async function () {
                const res = await axios.get(`/api/group/list?userId=${this.userId}`)
                const groupList = res.data;
                if (groupList && groupList.length !== 0) {
                    const group = groupList[0];
                    this.activeGroup = await this.fetchGroupDetail(group.id)
                    this.groupList = groupList
                }
            },

            refreshGroupPrice: async function () {
                const res = await axios.get(`/api/group/refresh?groupId=${this.activeGroup.id}`)
                this.activeGroup = res.data
            },
            changeActiveGroup: async function (active) {
                const activeIdx = parseInt(active);
                if (isNaN(activeIdx)) {
                    return
                }
                const activeId = this.groupList[activeIdx].id
                if (activeId === this.activeGroup.id) {
                    return
                }
                this.activeGroup = await this.fetchGroupDetail(this.groupList[activeIdx].id);
            },
            deleteGroup: async function () {
                const res = await axios.delete(`/api/group?groupId=${this.activeGroup.id}`)
                if (res.status === 200) {
                    await this.fetchGroups()
                    this.activeName = 0
                }
            },
            exportGroup: function (group) {
                const result = {
                    name: group.name,
                    cash: group.cash
                }
                result.items = group.groupItemList
                    .filter(item => item.code)
                    .map(item => ({
                        code: item.code,
                        count: item.count,
                        sort: item.sort
                    }))
                const jsonStr = JSON.stringify(result)
                const blob = new Blob([jsonStr])
                let a = document.createElement('a')
                a.download = `${result.name}.json`
                a.href = URL.createObjectURL(blob)
                a.style.display = 'none'
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
            },
            snapshotPng: function (idx) {
                // const node = document.getElementById(`groupTable${idx}`)
                const node = this.$refs[`groupTable${idx}`][0].$el
                htmlToImage.toPng(node)
                    .then(dataUrl => this.snapshotImg = dataUrl)
            }
        },

        watch: {
            activeGroup: function (activeGroup) {
                this.groupItemList =  activeGroup.groupItemList || []
                this.groupItemList.push({
                    cash: true,
                    name: '现金及现金等价物',
                    total: activeGroup.cash,
                    position: activeGroup.cashPosition
                })

                let total = 0
                this.groupItemList.forEach(item => total += item.total)
                this.groupItemList.push({
                    code: `${moment().format('yyyy/MM/DD')}`,
                    cash: true,
                    name: '汇总',
                    total: total.toFixed(2),
                    last: true
                })

                const d = new Date(this.activeGroup.createTime)
                this.activeGroup.createTimeStr = `${d.toLocaleDateString()}`
            }
        },

        mounted: function () {
            this.fetchGroups()
        }
    })
</script>
</html>
